package com.wellsoft.mobileoa.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wellsoft.mobileoa.FuncPageActivity;
import com.wellsoft.mobileoa.LoginActivity;
import com.wellsoft.mobileoa.R;
import com.wellsoft.mobileoa.dbmodel.ContactInfo;
import com.wellsoft.mobileoa.utils.action.GoBackAction;
import com.wellsoft.mobileoa.utils.view.DataView;
import com.wellsoft.mobileoa.utils.view.FormView;
import com.wellsoft.mobileoa.utils.view.FunctionView;
import com.wellsoft.mobileoa.utils.view.JGGView;
import com.wellsoft.mobileoa.utils.view.PostFailedView;
import com.wellsoft.mobileoa.utils.view.RadioView;
import com.wellsoft.mobileoa.wsmodel.WSOA_Action;
import com.wellsoft.mobileoa.wsmodel.WSOA_Dept;
import com.wellsoft.mobileoa.wsmodel.WSOA_DownloadUnit_Request;
import com.wellsoft.mobileoa.wsmodel.WSOA_DownloadUnit_Response;
import com.wellsoft.mobileoa.wsmodel.WSOA_Page;
import com.wellsoft.mobileoa.wsmodel.WSOA_PageListItem;
import com.wellsoft.mobileoa.wsmodel.WSOA_PageMenu;
import com.wellsoft.mobileoa.wsmodel.WSOA_PostField;
import com.wmobile.utils.BaseObject;
import com.wmobile.utils.ServiceResponse;

import android.R.integer;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.text.TextPaint;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public abstract class BaseView extends View {

	protected BaseActivity baseActivity;
	protected WSOA_Page page;
	protected String url;
	protected List<View> menuButtons;
	protected List<View> menuBars;
	protected int menuBarIndex = -1;
	protected ViewGroup selfView;
	protected boolean hasEdited;
	protected boolean isNewPageLoading = false;
	protected Boolean isExecuting = false;
	private GestureDetector toolBarGd = null;
	protected LinearLayout barContainer;
	protected ToolBarHorizontalScrollView toolBarScroller;
	int width = 0;

	public boolean isNewPageLoading() {
		return isNewPageLoading;
	}

	public void setNewPageLoading(boolean isNewPageLoading) {
		this.isNewPageLoading = isNewPageLoading;
	}

	public boolean getHasEdited() {
		return hasEdited;
	}

	public void setHasEdited(boolean hasEdited) {
		this.hasEdited = hasEdited;
	}

	public BaseActivity getBaseActivity() {
		return baseActivity;
	}

	public void setBaseActivity(BaseActivity baseActivity) {
		this.baseActivity = baseActivity;
	}

	public WSOA_Page getPage() {
		return page;
	}

	public void setPage(WSOA_Page page) {
		this.page = page;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public List<View> getMenuButtons() {
		return menuButtons;
	}

	public void setMenuButtons(List<View> menuButtons) {
		this.menuButtons = menuButtons;
	}

	public ViewGroup getSelfView() {
		return selfView;
	}

	public void setSelfView(ViewGroup selfView) {
		this.selfView = selfView;
	}

	public static BaseView CreateBaseViewFactory(BaseActivity baseActivity,
			WSOA_Page page, String url) {
		if (page.getPageType().equals("a")) {
			return new JGGView(baseActivity, page, url);
		} else if (page.getPageType().equals("b")) {
			return new FunctionView(baseActivity, page, url);
		} else if (page.getPageType().equals("c")) {
			return new DataView(baseActivity, page, url);
		} else if (page.getPageType().equals("d")
				|| page.getPageType().equals("s")) {
			return new FormView(baseActivity, page, url);
		} else if (page.getPageType().equals("g")) {
			return new RadioView(baseActivity, page, url);
		} else if (page.getPageType().equals("fail")) {
			return new PostFailedView(baseActivity, page, url);
		}
		return null;
	}

	public BaseView(BaseActivity baseActivity) {
		super(baseActivity);
	}

	public void initTitleBar(View view) {
		TextView titleTv = (TextView) view.findViewById(R.id.titleview_titletv);
		Button backBtn = (Button) view.findViewById(R.id.titleview_backbtn);
		Button homeBtn = (Button) view.findViewById(R.id.titleview_homebtn);

		titleTv.setText(page.getPageTitle().getMessage());
		backBtn.setOnClickListener(backOnClickListener);
		backBtn.setOnTouchListener(onTitleBackTouchListener);
		backBtn.setTag(view);
		homeBtn.setOnClickListener(homeOnClickListener);
		homeBtn.setOnTouchListener(onTitleHomeTouchListener);
		homeBtn.setTag(view);
	}

	OnTouchListener onTitleHomeTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			View titleView = (View) v.getTag();
			ImageView iv = (ImageView) titleView
					.findViewById(R.id.titleview_homeiv);
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				onTitleTouchDown(iv);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				onTitleTouchUp(iv);
			} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
				onTitleTouchUp(iv);
			} else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
				onTitleTouchUp(iv);
			}
			return false;
		}
	};

	protected OnTouchListener onTitleBackTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			View titleView = (View) v.getTag();
			ImageView iv = (ImageView) titleView
					.findViewById(R.id.titleview_backiv);
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				onTitleTouchDown(iv);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				onTitleTouchUp(iv);
			} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
				onTitleTouchUp(iv);
			} else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
				onTitleTouchUp(iv);
			}
			return false;
		}
	};

	public void onTitleTouchDown(ImageView v) {
		v.setAlpha(127);
	}

	public void onTitleTouchUp(ImageView v) {
		v.setAlpha(255);
	}

	public void initToolBar(View view) {
		WindowManager wm = (WindowManager) baseActivity
				.getSystemService(Context.WINDOW_SERVICE);

		width = wm.getDefaultDisplay().getWidth();
		menuBars = new ArrayList<View>();

		View tmpView = LayoutInflater.from(baseActivity).inflate(
				R.layout.functiontoolsubbar, null);
		menuBars.add(tmpView);

		tmpView.setLayoutParams(new LayoutParams(width, SystemConfig.dip2px(
				baseActivity, 55)));

		LinearLayout currentHorizontalLl = (LinearLayout) tmpView
				.findViewById(R.id.functiontoolbar_buttoncontainerll);

		int letterSize = 16;
		int remainWidth = width - SystemConfig.dip2px(baseActivity, letterSize)
				* 2;
		int spaceWidth = SystemConfig.dip2px(baseActivity, 4);

		// LinearLayout.LayoutParams params = new
		// LinearLayout.LayoutParams(width,
		// SystemConfig.dip2px(baseActivity, 55));
		// params.setMargins(SystemConfig.dip2px(baseActivity, 1), 0,
		// SystemConfig.dip2px(baseActivity, 1), 0);
		//
		// tmpView.setLayoutParams(params);

		if (page.getPageMenus() != null) {
			for (int i = page.getPageMenus().size() - 1; i >= 0; i--) {
				if (page.getPageMenus().get(i).getIsHidden() != null
						&& page.getPageMenus().get(i).getIsHidden().equals("1")) {
					page.getPageMenus().remove(i);
				}
			}
			menuButtons = new ArrayList<View>();
			for (WSOA_PageMenu pageMenu : page.getPageMenus()) {
				LinearLayout buttonView = (LinearLayout)LayoutInflater.from(baseActivity).inflate(
						R.layout.functiontoolbaritem, null);

				TextView titleTv = (TextView) buttonView
						.findViewById(R.id.functiontoolbaritem_icontv);
				titleTv.setText(pageMenu.getMessage());

				ImageView iconIv = (ImageView) buttonView
						.findViewById(R.id.functiontoolbaritem_iconiv);
				int indentify = this
						.getBaseActivity()
						.getResources()
						.getIdentifier(
								baseActivity.getPackageName() + ":drawable/"
										+ pageMenu.getImg(), null, null);
				if (indentify > 0) {
					iconIv.setImageResource(indentify);
				}

				TextPaint paint = titleTv.getPaint();
				float len = paint.measureText(pageMenu.getMessage());
				int btnWidth;
				if (len < SystemConfig.dip2px(baseActivity, 72)) {
					btnWidth = SystemConfig.dip2px(baseActivity, 72);
				} else {
					btnWidth = (int) (len + 0.5);
				}

				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
						btnWidth, LinearLayout.LayoutParams.MATCH_PARENT);
				params.setMargins(spaceWidth, 0, spaceWidth, 0);
				buttonView.setLayoutParams(params);

				buttonView.setOnClickListener(onMenuButtonClickedListener);
				buttonView.setTag(pageMenu);
				menuButtons.add(buttonView);
				buttonView.setOnTouchListener(onMenuTouchListener);

				if (remainWidth < btnWidth) {
					tmpView = LayoutInflater.from(baseActivity).inflate(
							R.layout.functiontoolsubbar, null);
					menuBars.add(tmpView);
					tmpView.setLayoutParams(new LayoutParams(width,
							SystemConfig.dip2px(baseActivity, 55)));

					currentHorizontalLl = (LinearLayout) tmpView
							.findViewById(R.id.functiontoolbar_buttoncontainerll);

					remainWidth = width
							- SystemConfig.dip2px(baseActivity, letterSize) * 2;
				}
				currentHorizontalLl.addView(buttonView);
				remainWidth -= btnWidth;
			}
		}
		for (int i = 0; i < menuBars.size(); i++) {
			if (i == 0) {
				ImageView leftArrowIv = (ImageView) menuBars.get(i)
						.findViewById(R.id.functiontoolbar_leftarrowiv);
				leftArrowIv.setAlpha(0);
			}
			if (i == menuBars.size() - 1) {
				ImageView rightArrowIv = (ImageView) menuBars.get(i)
						.findViewById(R.id.functiontoolbar_rightarrowiv);
				rightArrowIv.setAlpha(0);
			}
		}
		if (menuBars.size() > 0) {
			toolBarGd = new GestureDetector(baseActivity,
					new ToolBarGestureListener());
			toolBarScroller = (ToolBarHorizontalScrollView) view
					.findViewById(R.id.functiontoolbar_barscrollcontainerthsv);
			barContainer = (LinearLayout) view
					.findViewById(R.id.functiontoolbar_barcontainerll);
			barContainer.setOnTouchListener(onToolBarListener);
			for (int i = 0; i < menuBars.size(); i++) {
				barContainer.addView(menuBars.get(i));
			}
			menuBarIndex = 0;
		}
	}

	OnTouchListener onToolBarListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (toolBarGd.onTouchEvent(event))
				return true;
			else
				return false;
		}
	};

	public class ToolBarGestureListener extends
			GestureDetector.SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if (velocityX < 0) {
				toolBarSliderLeft();
			} else {
				toolBarSliderRight();
			}
			return true;
		}
	}

	public void toolBarSliderLeft() {
		if (menuBarIndex == menuBars.size() - 1 || menuBars.size() == 1)
			return;

		toolBarScroller.scrollTo(width * (menuBarIndex + 1), 0);

		TranslateAnimation outAnimation = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT,
				0, Animation.RELATIVE_TO_PARENT, 0,
				Animation.RELATIVE_TO_PARENT, 0);
		outAnimation.setDuration(1000);
		outAnimation.setStartOffset(0);
		// outAnimation.setAnimationListener(new ScrollAnimationListener(
		// menuBarIndex + 1));
		barContainer.startAnimation(outAnimation);

		// TranslateAnimation outAnimation = new TranslateAnimation(
		// Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT,
		// -1, Animation.RELATIVE_TO_PARENT, 0,
		// Animation.RELATIVE_TO_PARENT, 0);
		// outAnimation.setDuration(1000);
		// outAnimation.setStartOffset(0);
		// outAnimation.setAnimationListener(new ScrollAnimationListener(
		// menuBarIndex + 1));
		// barContainer.startAnimation(outAnimation);

		menuBarIndex++;
	}

	public void toolBarSliderRight() {
		if (menuBarIndex == 0 || menuBars.size() == 1)
			return;
		toolBarScroller.scrollTo(width * (menuBarIndex - 1), 0);

		TranslateAnimation outAnimation = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, -1, Animation.RELATIVE_TO_PARENT,
				0, Animation.RELATIVE_TO_PARENT, 0,
				Animation.RELATIVE_TO_PARENT, 0);
		outAnimation.setDuration(1000);
		outAnimation.setStartOffset(0);
		// outAnimation.setAnimationListener(new ScrollAnimationListener(
		// menuBarIndex - 1));
		barContainer.startAnimation(outAnimation);

		// TranslateAnimation outAnimation = new TranslateAnimation(
		// Animation.RELATIVE_TO_PARENT, 0,
		// Animation.RELATIVE_TO_PARENT, 1,
		// Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT,
		// 0);
		// outAnimation.setDuration(1000);
		// outAnimation.setStartOffset(0);
		// outAnimation.setAnimationListener(new ScrollAnimationListener(
		// menuBarIndex - 1));
		// barContainer.startAnimation(outAnimation);

		menuBarIndex--;
	}

	private class ScrollAnimationListener implements AnimationListener {
		private int index;

		public ScrollAnimationListener(int index) {
			this.index = index;
		}

		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			toolBarScroller.scrollTo(width * index, 0);
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
		}
	}

	OnTouchListener onMenuTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (toolBarGd.onTouchEvent(event)) {
				onMenuTouchUp(v);
				return true;
			} else {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					onMenuTouchDown(v);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					onMenuTouchUp(v);
				} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
					onMenuTouchUp(v);
				} else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
					onMenuTouchUp(v);
				}
				return false;
			}
		}
	};

	public void onMenuTouchDown(View v) {
		v.setBackgroundColor(Color.argb(255, 255, 255, 255));
	}

	public void onMenuTouchUp(View v) {
		v.setBackgroundColor(Color.argb(0, 0, 0, 0));
	}

	protected OnClickListener backOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			goBackActivity();
		}

	};

	OnClickListener homeOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			baseActivity.returnHomeActivity();
		}
	};

	OnClickListener onMenuButtonClickedListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			synchronized (BaseView.this.isExecuting) {
				if (isExecuting) {
					return;
				}
				isExecuting = true;
				AlertDialog alertDialog = baseActivity.showWaitingDialog();
				WSOA_PageMenu pageMenu = (WSOA_PageMenu) v.getTag();
				ServiceResponse response = BaseAction.executeActions(
						pageMenu.getActionID(), pageMenu.getAction(),
						BaseView.this);
				alertDialog.dismiss();
				isExecuting = false;
				if (!response.getExeFlag()) {
					baseActivity.showMessage(response.getMessage());
					return;
				}
			}
		}
	};

	public ViewGroup DrawSelf() {
		return null;
	}

	public List<WSOA_PostField> getValue() {
		return new ArrayList<WSOA_PostField>();
	}

	public BaseWidget getWidgetById(String widgetId) {
		return null;
	}

	public void addNextPage(WSOA_Page page) {

	}

	public void resetView() {

	}

	public void selectAllItem() {

	}

	public ServiceResponse checkValid() {
		return new ServiceResponse(true);
	}

	public void goBackActivity() {
		synchronized (BaseView.this.isExecuting) {
			if (isExecuting) {
				return;
			}
			isExecuting = true;
			if (baseActivity.getBaseView().getClass().getSimpleName()
					.equals(JGGView.class.getSimpleName())) {
				BaseActivity.returnLoginActivity();
				isExecuting = false;
				return;
			}
			AlertDialog alertDialog = baseActivity.showWaitingDialog();
			WSOA_Action wsAction = new WSOA_Action();
			wsAction.setFuncType("u");
			GoBackAction action = new GoBackAction(wsAction, BaseView.this);
			action.excuteAction();
			isExecuting = false;
		}
	}
}
